﻿using System;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(UIGrid))]
public class LoopScrollView : MonoBehaviour
{
    private Transform cachedTransform;
    private UIGrid grid;
    public List<UIWidget> itemList = new List<UIWidget>();
    public string perfix = string.Empty;
    private Vector4 posParam;

    private void Awake()
    {
        this.cachedTransform = base.transform;
        this.grid = base.GetComponent<UIGrid>();
        float cellWidth = this.grid.cellWidth;
        float cellHeight = this.grid.cellHeight;
        this.posParam = new Vector4(cellWidth, cellHeight, (this.grid.arrangement != UIGrid.Arrangement.Horizontal) ? ((float) 0) : ((float) 1), (this.grid.arrangement != UIGrid.Arrangement.Vertical) ? ((float) 0) : ((float) 1));
    }

    private void LateUpdate()
    {
        if (this.itemList.Count > 1)
        {
            int index = -1;
            int num2 = -1;
            int num3 = 0;
            bool isVisible = this.itemList[0].isVisible;
            bool flag2 = this.itemList[this.itemList.Count - 1].isVisible;
            if (isVisible != flag2)
            {
                if (isVisible)
                {
                    index = this.itemList.Count - 1;
                    num2 = 0;
                    num3 = -1;
                }
                else if (flag2)
                {
                    index = 0;
                    num2 = this.itemList.Count - 1;
                    num3 = 1;
                }
                if (index > -1)
                {
                    UIWidget item = this.itemList[index];
                    Vector3 vector = new Vector3((num3 * this.posParam.x) * this.posParam.z, (num3 * this.posParam.y) * this.posParam.w, 0f);
                    item.cachedTransform.localPosition = this.itemList[num2].cachedTransform.localPosition + vector;
                    this.itemList.RemoveAt(index);
                    this.itemList.Insert(num2, item);
                }
            }
        }
    }

    public void Refresh()
    {
        this.itemList.Clear();
        for (int i = 0; i < this.cachedTransform.childCount; i++)
        {
            UIWidget component = this.cachedTransform.GetChild(i).GetComponent<UIWidget>();
            component.name = string.Format("{0}_{1:D3}", this.perfix, this.itemList.Count);
            this.itemList.Add(component);
        }
    }

    private void Start()
    {
        if (this.itemList.Count <= 0)
        {
            for (int i = 0; i < this.cachedTransform.childCount; i++)
            {
                UIWidget component = this.cachedTransform.GetChild(i).GetComponent<UIWidget>();
                component.name = string.Format("{0}_{1:D3}", this.perfix, this.itemList.Count);
                this.itemList.Add(component);
            }
        }
    }
}

